<template>
  <div class="app-container">
    <!-- <div class="header_title_box">
      <h2>出库单管理</h2>
    </div> -->
    <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch">
      <div class="mb10">
        <el-button size="small" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
      </div>
    </form-selections>
    <div style="margin-top:20px" />
    <!-- 出库订单类型 -->
    <el-tabs v-model="queryParam.source" type="card" class="margin-bottom-0" @tab-click="handleSearch">
      <el-tab-pane label="销售出库" name="sales">
        <!-- <div class="operation_button_box">
          <el-button v-action="'outboundOrder@export'" size="middle" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        </div> -->
      </el-tab-pane>
      <el-tab-pane label="调拨出库" name="allot">
        <!-- <div class="operation_button_box">
          <el-button v-action="'outboundOrder@export'" size="middle" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        </div> -->
      </el-tab-pane>
      <el-tab-pane label="盘点出库" name="check">
        <!-- <div class="operation_button_box">
          <el-button v-action="'outboundOrder@export'" size="middle" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        </div> -->
      </el-tab-pane>
      <el-tab-pane label="手工出库" name="manual">
        <!-- <div class="operation_button_box">
          <el-button v-action="'outboundOrder@save'" size="middle" type="primary" icon="el-icon-circle-plus-outline" @click="toAddoutboundOrder">创建出库单</el-button>
          <el-button v-action="'outboundOrder@SubmitAudit'" size="middle" type="primary" @click="submitAudit">提交审核</el-button>
          <el-button v-action="'outboundOrder@changeAuditStatus'" size="middle" type="primary" @click="showAuditDialog">审核</el-button>
          <el-button v-action="'outboundOrder@batchDelete'" size="middle" type="danger" @click="dels(0)">批量删除</el-button>
          <el-button size="middle" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        </div> -->
      </el-tab-pane>
    </el-tabs>
    <div class="select_flex">
      <div v-show="queryParam.source === 'manual'" class="operation_button_box">
        <el-button v-action="'outboundOrder@save'" size="small" type="primary" icon="el-icon-circle-plus-outline" @click="toAddoutboundOrder">创建出库单</el-button>
        <el-button v-action="'outboundOrder@SubmitAudit'" size="small" type="primary" @click="submitAudit">提交审核</el-button>
        <el-button v-action="'outboundOrder@changeAuditStatus'" size="small" type="primary" @click="showAuditDialog">审核</el-button>
        <el-button v-action="'outboundOrder@batchDelete'" size="small" type="danger" @click="dels(0)">批量删除</el-button>
        <el-button v-action="'outboundOrder@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
      </div>
      <div v-show="queryParam.source !== 'manual'" class="operation_button_box">
        <el-button v-action="'outboundOrder@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <div v-loading="loading">
      <el-table :data="data" border fit :row-class-name="tableRowClassName" :max-height="screenHeigh" @selection-change="handleSelectMulti">
        <el-table-column key="selection" type="selection" width="51" align="center" />
        <el-table-column v-if="queryParam.source === 'manual'" key="opretion" label="操作" align="center" width="135" fixed>
          <template slot-scope="scope">
            <span v-if="scope.row.audit_status !== 2" v-action="'outboundOrder@update'" class="edit_style" style="margin: 0;" @click="handleUpdate(scope.row)">编辑</span>
            <span v-if="scope.row.audit_status !== 2" v-action="'outboundOrder@batchDelete'" class="delete_style" style="margin: 0;" @click="dels(scope.row.id)">删除</span>
          </template>
        </el-table-column>
        <el-table-column key="code" label="出库单号" align="center" min-width="248">
          <template slot-scope="scope">
            <code-item :code="scope.row.code" @click="showInfoDialog(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column key="virtual_warehouse" label="出库虚拟仓" prop="virtual_warehouse" align="center" width="196" />
        <el-table-column key="entity_warehouse" label="出库实体仓" prop="entity_warehouse" align="center" width="236" />
        <el-table-column key="product" align="center" label="系统SKU|商品名称|数量" width="400px" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.products" :key="index">
              <el-divider v-if="index !==0" class="line_style" />
              <span>{{ item.goods_code }}<b>|</b>{{ item.goods_name }} <b>|</b>{{ item.number }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="queryParam.source !== 'manual'" key="parts" align="center" label="配件SKU|配件名称|数量" width="300px" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.parts" :key="index">
              <el-divider v-if="index !==0" class="line_style" />
              <span>{{ item.goods_code }}<b>|</b>{{ item.goods_name }}<b>|</b>{{ item.number }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="queryParam.source === 'manual'" key="audit_status" label="审核状态" prop="audit_status" align="center" width="222">
          <template slot-scope="scope">
            <span>{{ statusMap[scope.row.audit_status] }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="queryParam.source === 'manual'" label="审核原因" prop="audit_status" align="center" width="112">
          <template slot-scope="scope">
            <span>{{ scope.row.audit_notes || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column key="created_by_name" label="创建人" prop="created_by_name" align="center" width="112" />
        <el-table-column key="created_at" label="创建时间" prop="created_at" align="center" width="174" />
        <el-table-column key="updated_by_name" label="修改人" prop="updated_by_name" align="center" width="112" />
        <el-table-column key="updated_at" label="修改时间" prop="updated_at" align="center" width="174" />
      </el-table>
      <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <audit-dialog ref="auditDialog" :base-fields="baseFields" :number-desc="numberDesc" :change-audit-url="changeAuditUrl" :info-url="infoUrl" @submit="auditHandler" />
    <warehouse-order-info-dialog ref="infoDialog" :base-fields="baseFields" :number-desc="numberDesc" />
    <!--下载字段选择-->
    <DownModul :url="exportUrl" :search-param="downLoadParams" :form-visible-down.sync="formVisibleDown" titel="仓库调拨单导出字段选择" :options-modul="optionsModul" />
  </div>
</template>

<script>
import formOperate from '../../../layout/mixin/formOperate'
import { action } from '@/directive/permission/index.js' // 权限判断指令
import auditDialog from '../components/auditDialog'
import warehouseOrderInfoDialog from '../components/warehouseOrderInfoDialog'
import codeItem from '../../../components/base/code'
import cacheList from '@/layout/mixin/cacheList'
import DownModul from '@/components/DownModul/index.vue'
export default {
  name: 'OutboundOrder', // 出库单
  components: {
    auditDialog,
    warehouseOrderInfoDialog,
    codeItem,
    DownModul
  },
  directives: {
    action
  },
  mixins: [formOperate, cacheList],
  data() {
    return {
      otherHeight: 395,
      componentName: 'OutboundOrder', // 出库单
      statusList: [
        {
          id: 0,
          name: '待提交'
        },
        {
          id: 1,
          name: '待审核'
        },
        {
          id: 2,
          name: '审核通过'
        },
        {
          id: -1,
          name: '审核驳回'
        }
      ], // 审核状态list
      statusMap: {
        0: '待提交',
        1: '待审核',
        2: '审核通过',
        '-1': '审核驳回'
      },
      formItems: [
        {
          label: '出库单号',
          key: 'code',
          type: 'input',
          placeholder: '请输入出库单号'
        },
        {
          label: '仓库名称',
          key: 'warehouse_name',
          type: 'input',
          placeholder: '请输入仓库名称'
        },
        {
          label: '商品SKU',
          key: 'goods_code',
          type: 'input',
          placeholder: '请输入商品SKU'
        },
        {
          label: '审核状态',
          key: 'audit_status',
          type: 'select',
          filterable: true,
          placeholder: '请选择审核状态',
          options: [
            {
              value: 0,
              label: '待提交'
            },
            {
              value: 1,
              label: '待审核'
            },
            {
              value: 2,
              label: '审核通过'
            },
            {
              value: -1,
              label: '审核驳回'
            }
          ]
        },
        {
          label: '创建时间',
          key: 'dateCreat',
          type: '',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        }
      ],
      url: '/outbound-order',
      queryParam: {
        code: '', // 出库单号
        audit_status: '', // 出库单审核状态
        source: 'sales' // 出库单类型
      }, // 搜索参数
      defaultQueryParam: ['source'], // 搜索参数不清空列表
      baseFields: [
        {
          id: 1,
          label: '出库单号',
          prop: 'code'
        },
        {
          id: 2,
          label: '出库实体仓',
          prop: 'entity_warehouse'
        },
        {
          id: 3,
          label: '出库虚拟仓',
          prop: 'virtual_warehouse'
        },
        {
          id: 4,
          label: '出库原因',
          prop: 'notes'
        }
      ],
      numberDesc: {
        label: '出库数量',
        prop: 'number'
      },
      changeAuditUrl: '/outbound-order/change-audit-status',
      infoUrl: '/outbound-order',
      exportUrl: '/outbound-order-export',
      cachePaths: [
        '/storage/outboundOrder/'
      ],
      optionsModul: [
        {
          key: 'code',
          label: '出库单号'
        },
        {
          key: 'entity_warehouse',
          label: '出库实体仓'
        },
        {
          key: 'virtual_warehouse',
          label: '出库虚拟仓'
        },
        {
          key: 'audit_status_text',
          label: '审核状态'
        },
        {
          key: 'goods_name',
          label: '商品名称'
        },
        {
          key: 'goods_code',
          label: '商品SKU'
        },
        {
          key: 'number',
          label: '商品数量'
        },
        {
          key: 'created_by_name',
          label: '创建人'
        },
        {
          key: 'created_at',
          label: '创建时间'
        }
      ]
    }
  },
  activated() {
    this.getList()
  },
  methods: {
    beforeSearch() {
      const vm = this
      const { dateCreat } = vm.queryParam
      if (dateCreat && dateCreat.length > 0) {
        vm.queryParam.start_at_creat = vm.queryParam.dateCreat[0]
        vm.queryParam.end_at_creat = vm.queryParam.dateCreat[1]
      } else {
        vm.queryParam.start_at_creat = ''
        vm.queryParam.end_at_creat = ''
      }
    },
    // 导出
    handleExport() {
      const vm = this
      // const { code, audit_status, source } = vm.queryParam
      // const params = { code, audit_status, source }
      // vm.handleExportxlsx(vm.exportUrl, params)
      vm.downLoadParams = vm.queryParam
      vm.formVisibleDown = true
    },
    /**
     * 去添加出库单
     * */
    toAddoutboundOrder() {
      const vm = this
      window.localStorage.removeItem('outboundOrder')
      vm.$router.push({ path: '/storage/outboundOrder/add' })
    },
    // 批量删除
    dels(id) {
      const vm = this
      let ids = []
      if (id) {
        ids.push(id)
      } else {
        ids = vm.selectedIds
      }
      vm.$confirm(`确定${id ? '' : '批量'}删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http.post('/outbound-order/batch-delete', { ids }).then((res) => {
          vm.$message.success('删除成功')
          vm.getList()
        })
      })
    },
    // 编辑出库单
    handleUpdate(row) {
      const vm = this
      if (row.audit_status === 2) {
        vm.$message.error('出库单已审核通过,不可编辑')
        return
      }
      window.localStorage.removeItem('outboundOrder')
      vm.$router.push({
        path: `/storage/outboundOrder/add/${row.id}`,
        query: { title: '编辑出库单' }
      })
    },
    // 提交审核
    submitAudit() {
      const vm = this
      if (vm.selectedIds.length <= 0) {
        vm.$message.error('请至少选择一条数据')
        return
      }
      // 判断列表是否都是 待提交状态
      const isEveryToSubmit = vm.data
        .filter((e) => vm.selectedIds.includes(e.id))
        .every((e) => [0, -1].includes(e.audit_status))
      if (isEveryToSubmit) {
        vm.$confirm(`确定提交审核吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          vm.$http
            .post('/outbound-order/submit-audit', { ids: vm.selectedIds })
            .then((res) => {
              vm.$message.success('提交审核成功')
              vm.getList()
            })
        })
      } else {
        vm.$message.error('选择数据须都是待提交或审核驳回状态')
      }
    },
    // 审核
    showAuditDialog() {
      const vm = this
      if (vm.selectedIds.length <= 0) {
        vm.$message.error('请至少选择一条数据')
        return
      }
      if (vm.selectedIds.length > 1) {
        vm.$message.error('请至多选择一条数据')
        return
      }
      const firstId = vm.selectedIds[0]
      const first = vm.data.find((e) => e.id === firstId)
      // 是否都是待审核状态
      if (first.audit_status !== 1) {
        vm.$message.error('选择数据必须是待审核状态')
        return
      }
      vm.$refs['auditDialog'].show({
        id: firstId,
        auditStatus: [
          { label: 2, name: '审核通过' },
          { label: -1, name: '审核驳回' }
        ]
      })
    },
    // 审核成功之后handler
    auditHandler() {
      const vm = this
      vm.getList()
    },
    // 确认出库
    enterWarehouse() {
      const vm = this
      if (vm.selectedIds.length <= 0) {
        vm.$message.error('请至少选择一条数据')
        return
      }
      if (vm.selectedIds.length > 1) {
        vm.$message.error('请至多选择一条数据')
        return
      }
      vm.$confirm(`确定提交出库吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = vm.selectedIds[0]
        vm.$http.put(`/outbound-order/in-stock/${id}`).then(() => {
          vm.$message.success('出库成功')
          vm.getList()
        })
      })
    },
    // 显示详情dialog
    showInfoDialog(info) {
      const vm = this
      vm.$refs.infoDialog.show({
        info,
        showParts: ['sales', 'allot', 'check'].indexOf(vm.queryParam.source) > -1,
        id: info.id,
        type: 'outbound'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.margin-bottom-0.el-tabs--card ::v-deep .el-tabs__header {
  margin-bottom: 0;
}
.operation_button_box ::v-deep .el-button + .el-button {
  margin-left: 14px;
}
</style>
